/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufjf.pos.controller.filtro;

import br.ufjf.pos.model.Usuario;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author ice
 */
@WebFilter(filterName = "SecurityFilter", urlPatterns = {"/*"}, dispatcherTypes = {DispatcherType.FORWARD, DispatcherType.ERROR, DispatcherType.REQUEST, DispatcherType.INCLUDE})
public class SecurityFilter implements Filter {
    
    private static final boolean debug = true;
    // The filter configuration object we are associated with.  If
    // this value is null, this filter instance is not currently
    // configured. 
    private FilterConfig filterConfig = null;
    
    public SecurityFilter() {
    }    
    
    /**
     *
     * @param request The servlet request we are processing
     * @param response The servlet response we are creating
     * @param chain The filter chain we are processing
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {
        
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response; 
        HttpSession ses = req.getSession();
        Usuario u = (Usuario) ses.getAttribute("usuario");

        String arq = req.getServletPath();
        
        String action = req.getParameter("action");
        
        if (
             ((u != null) && (!arq.contains(".jsp"))) ||
             (arq.equals("/index.jsp")) ||
             (arq.equals("/home.jsp")) ||
             (arq.equals("/usuarioLogin.jsp")) ||
             (arq.equals("/controller")) ||
             (arq.equals("/Logar")) ||   
             (arq.equals("erro.jsp")) ||
             (arq.equals("/acesso.html")) ||   
             (arq.contains(".css")) ||
             (arq.contains(".jpg")) ||
             (arq.contains(".png")) ||
             (action.equals("UsuarioLogin"))) {
            
             chain.doFilter(request, response); 
            
        } else {
            
            resp.sendRedirect("acesso.html");
        }

    }

    
    /**
     * Destroy method for this filter 
     */
    public void destroy() {        
    }

    /**
     * Init method for this filter 
     */
    public void init(FilterConfig filterConfig) {        
        this.filterConfig = filterConfig;
        if (filterConfig != null) {
            if (debug) {                
                //log("SecurityFilter:Initializing filter");
            }
        }
    }

   
}
